import Link from '@/core/components/elements/Link/Link'
import Spinner from '@/core/components/elements/Spinner/Spinner'
import BasicLayout from '@/core/components/layouts/BasicLayout'
import { createSlug, getIdFromSlug } from '@/core/utils/slug'
import useBlog from '@/lib/blog/hooks/useBlog'
import { useRouter } from 'next/router'

export default function BlogDetail() {
  const router = useRouter()
  const { slug = '' } = router.query
  const id = getIdFromSlug(slug)
  const { blog } = useBlog({ id })

  const parsedContent = blog.data?.content?.replaceAll(
    'src="/web/image',
    `src="${process.env.NEXT_PUBLIC_ODOO_HOST}/web/image`
  )

  const contentClassNames = ` 
      prose 
      prose-gray 
      prose-a:text-red_r-10 
      prose-a:no-underline
      prose-p:my-4
      prose-headings:mt-6
      prose-headings:mb-3
      prose-headings:font-medium
      prose-h1:text-title-sm
      prose-h2:text-h-md
      prose-img:my-0 
      prose-img:mb-1 
      prose-img:inline-block
      prose-hr:my-3
      max-w-none
    `

  return (
    <BasicLayout>
      {blog.isLoading && (
        <div className='flex justify-center my-6'>
          <Spinner className='w-6 text-gray_r-12/50 fill-gray_r-12' />
        </div>
      )}

      {blog.isFetched && (
        <div className='container mx-auto p-4 md:p-0 my-0 md:my-10'>
          <h1 className='text-title-sm md:text-title-md font-semibold mb-2 leading-10'>
            {blog.data?.title}
          </h1>
          <h2 className='leading-6 text-gray_r-12/90 mb-8'>
            Diposting pada tanggal {blog.data?.postDate}{' '}
            {blog.data?.category?.id && `di ${blog.data?.category?.name}`}
          </h2>

          <article
            className={contentClassNames}
            dangerouslySetInnerHTML={{ __html: parsedContent }}
          />
        </div>
      )}
    </BasicLayout>
  )
}
